import fs from 'fs'
import cheerio from 'cheerio'
import { Analyzer } from './crowller'

interface Course {
  descs: string
  imgSrc: string | undefined
}

interface CourseResult {
  time: number
  data: Course[]
}

interface Content {
  [propName: number]: Course[]
}

export default class DellAnalyzer implements Analyzer {
  private constructor() {}
  private static instanse: DellAnalyzer
  static getInstance() {
    if (!DellAnalyzer.instanse) {
      DellAnalyzer.instanse = new DellAnalyzer()
    }
    return DellAnalyzer.instanse
  }
  private getJsonInfo(html: string) {
    const $ = cheerio.load(html)
    const courseItems = $('.jtxm')

    const courseInfos: Course[] = []
    courseItems.map((index, element) => {
      const descs = $(element).find('h4').text().trim()
      const imgSrc = $(element).find('img').attr('src')
      courseInfos.push({ descs, imgSrc })
    })
    return {
      time: new Date().getTime(),
      data: courseInfos
    }
  }

  // 生成需要保存的 JSON
  private generateJsonContent(courseInfo: CourseResult, filePath: string) {
    let fileContent: Content = {}
    // 判断文件路径是否存在,如果存在就把里面的内容存给 fileContent
    if (fs.existsSync(filePath)) {
      fileContent = JSON.parse(fs.readFileSync(filePath, 'utf-8'))
    }
    fileContent[courseInfo.time] = courseInfo.data
    return fileContent
  }

  public analyze(html: string, filePath: string) {
    const courseInfo = this.getJsonInfo(html)
    const fileContent = this.generateJsonContent(courseInfo, filePath)
    return JSON.stringify(fileContent)
  }
}
